package cn.sundat.web.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
/**
 * 文件下载action
 * author LeeLiang
 */
public class DownLoadAction extends ActionSupport{
	
	
	public String down() throws Exception {
		//获取要下载的文件的名字
		String fileName = ServletActionContext.getRequest().getParameter("fileName");
		//将文件名转码
		fileName = new String(fileName.getBytes("iso8859-1"),"utf-8");
		//截取图片的名字
//		String newFileName = fileName.substring(fileName.indexOf("/"));
		//获取文件存放的路径
		String realPath = ServletActionContext.getServletContext().getRealPath("/");
		//获取要下载的文件
		File file = new File(realPath+File.separator+fileName);
		if(!file.exists()) {
			ServletActionContext.getRequest().setAttribute("msg", "文件已被删除");
			return "msg";
		}
		//响应头设置
		ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		//读取文件流
		FileInputStream is = new FileInputStream(file);
		//写出文件流
		ServletOutputStream os = ServletActionContext.getResponse().getOutputStream();
		//创建缓存流
		byte[] bys = new byte[1024];
		int len = 0;
		while((len=is.read(bys))>0) {
			os.write(bys, 0, len);
		}
		//关闭流
		is.close();
		os.close();
		
		return NONE;
	}
	
	public String login() {
		System.out.println("登录进来");
		return NONE;
	}
	
}
